#! /bin/bash
# 解决 cursor appimage sandbox 问题：解压后修改权限运行

# Default install directory
install_dir=~/Applications/cursor

# A function to display usage information
usage() {
    echo "解决 cursor appimage sandbox 问题：解压后到某个目录后修改权限运行"
    echo "Usage: $0 [options] <cursor_appimage_file>"
    echo "Installs or updates the cursor editor from an AppImage file."
    echo
    echo "Options:"
    echo "  -d, --dest DIR  Set the installation directory (default: $install_dir)"
    echo "  -h, --help      Display this help message and exit."
    echo
}

# Parse command-line options using getopt
TEMP=$(getopt -o hd: --long help,dest: -n "$0" -- "$@")

if [ $? != 0 ]; then
    echo "Terminating..." >&2
    exit 1
fi

# Note the quotes around '$TEMP': they are essential!
eval set -- "$TEMP"

while true; do
    case "$1" in
    -h | --help)
        usage
        exit 0
        ;;
    -d | --dest)
        install_dir="$2"
        shift 2
        ;;
    --)
        shift
        break
        ;;
    *)
        echo "Internal error!"
        exit 1
        ;;
    esac
done


# read first arg as the cursor file path
cursor_file="$1"

if [ -z "$cursor_file" ]; then
    echo "Error: Cursor AppImage file not provided."
    usage
    exit 1
fi

# 规范化用户输入
install_dir=`realpath "$install_dir"`
if test -d "$install_dir"; then
    # back up old cursor, backup dir is {install_dir}-{today}
    backup_dir=$install_dir-$(date +%Y-%m-%d)
    if test -d "$backup_dir"; then
        echo "Backup directory $backup_dir already exists"
        exit 1
    else
        echo "Backing up old cursor to $backup_dir"
        mv "$install_dir" "$backup_dir"
    fi
fi


# make temp dir
tmpdir=$(mktemp -d)
echo "Using tempdir $tmpdir"
cp "$cursor_file" "$tmpdir/"

filename=$(basename "$cursor_file")
cd "$tmpdir"

chmod u+x "$filename"

# install to install_dir
./"$filename" --appimage-extract > /dev/null 2>&1
mv squashfs-root "$install_dir"

cd "$install_dir"
chrome_file=$(find . -name 'chrome-sandbox' -type f)
sudo chown root:root "$chrome_file"
sudo chmod 4755 "$chrome_file"
